<?php
namespace Admin\Controller;
use Common\Controller\BackendController;

class BrandController extends BackendController{
	public $_tbconfig='';
	
    public function _initialize()
    {
        parent::_initialize();
        $this->_brandmod = D('Brand');
        $this->_cate_mod = D('BrandCate');
        
        $api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
        $this->_tbconfig = unserialize($api_config);
    }
    
    public function _before_index()
    {
        $res = $this->_cate_mod->field('id,name')->select();
        $cate_list = array();
        foreach ($res as $val) {
            $cate_list[$val['id']] = $val['name'];
        }
        $this->assign('cate_list', $cate_list);
        $this->sort = 'ordid ASC,';
        $this->order = 'id DESC';
    }
    public function ajax_upload_img()
    {
        $type = $this->_get('type', 'trim', 'img');
        if (!empty($_FILES[$type]['name'])) {
            $date = date('ym/d/');
            $result = $this->_upload($_FILES[$type], 'brand/' . $date);
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $dr = $date . $result['info'][0]['savename'];
                $this->ajaxReturn(1, L('operation_success'), C('itk_attach_path') . 'brand/' . $dr);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }
    public function move()
    {
        if (IS_POST) {
            $pid['pid'] = $this->_post('pid', 'intval');
            $ids = $this->_post('ids');
            $ids_arr = explode(',', $ids);
            $data['cate_id'] = $pid['pid'];
            $this->_brandmod->where(array('id' => array('in', $ids)))->save($data);
            $this->ajaxReturn(1, L('operation_success'), '', 'move');
        } else {
            $ids = trim($this->_request('id'), ',');
            $this->assign('ids', $ids);
            $resp = $this->fetch();
            $this->ajaxReturn(1, '', $resp);
        }
    }
    protected function _search()
    {
        $map = array();
        ($time_start = $this->_request('time_start', 'trim')) && ($map['add_time'][] = array('egt', strtotime($time_start)));
        ($time_end = $this->_request('time_end', 'trim')) && ($map['add_time'][] = array('elt', strtotime($time_end) + (24 * 60 * 60 - 1)));
        ($xy = $this->_request('xy', 'trim')) && ($map['xy'][] = array('egt', $xy));
        ($nick = $this->_request('nick', 'trim')) && ($map['nick'] = array('like', '%' . $nick . '%'));
        ($sellerId = $this->_request('sellerId', 'trim')) && ($map['sellerId'] = array('like', '%' . $sellerId . '%'));
        $cate_id = $this->_request('cate_id', 'intval');
        ($title = $this->_request('title', 'trim')) && ($map['title'] = array('like', '%' . $title . '%'));
        if ($cate_id) {
            $id_arr = $this->_cate_mod->get_child_ids($cate_id, true);
            $map['cate_id'] = array('IN', $id_arr);
            $spid = $this->_cate_mod->where(array('id' => $cate_id))->getField('spid');
            if ($spid == 0) {
                $spid = $cate_id;
            } else {
                $spid .= $cate_id;
            }
        }
        $this->assign('search', array('time_start' => $time_start, 'time_end' => $time_end, 'xy' => $xy, 'sellerId' => $sellerId, 'selected_ids' => $spid, 'cate_id' => $cate_id, 'title' => $title));
        return $map;
    }
    public function add()
    {
        if (IS_POST) {
            if (FALSE === ($pid = $this->_brandmod->create())) {
                $this->error($this->_brandmod->getError());
            }
            $pid['cate_id'] = $_POST['cate_id'];
            $pid['activityId'] = $_POST['activityId'];
            if (!trim($pid['cate_id'])) {
                $this->error('请选择品牌所属分类');
            }
            if ($this->_brandmod->where(array('activityId' => $pid['activityId']))->count()) {
                $this->error('品牌已存在，请更换其他品牌');
            }
            $pid['sellerId'] = $_POST['sellerId'];
            $pid['logo'] = $_POST['logo'];
            $pid['pic'] = $_POST['pic'];
            $pid['newpic'] = $_POST['newpic'];
            $pid['banner'] = $_POST['banner'];
            $pid['title'] = $_POST['title'];
            $pid['desc'] = $_POST['desc'];
            $pid['hot'] = $_POST['hot'];
            $pid['click_url'] = $_POST['click_url'];
            $pid['seo_title'] = $_POST['seo_title'];
            $pid['seo_keys'] = $_POST['seo_keys'];
            $pid['seo_desc'] = $_POST['seo_desc'];
            
            $pid['start_time'] = strtotime($_POST['start_time']);
            $pid['end_time'] = strtotime($_POST['end_time']);
	
            $brandmod = $this->_brandmod->add($pid);
            if (!$brandmod) {
                $this->error(l('operation_failure'));
            }
            $this->success(l('operation_success'));
        } else {
            $this->display();
        }
    }
    
    // 采集单个商品
    public function ajaxGetItem()
    {
        if (!isset($_REQUEST['link'])) {
            $this->ajaxReturn(0, '未传入商品链接');
        }
        $tb_top = $this->_get_top();
        $req = $tb_top->load_api('ItaokeBrandGetRequest');
		$req->setFields($_REQUEST['link']);
        $resp = (array)$tb_top->execute($req);
        if($resp['status'] != '0000')
        {
        	$this->ajaxReturn(0, $resp['msg']);
        }
		else
		{
			$resp['data']['end_time'] = date('Y-m-d H:i:s',$resp['data']['end_time'] );
			$resp['data']['start_time'] = date('Y-m-d H:i:s',$resp['data']['start_time'] );
			$this->ajaxReturn(1, '', $resp['data']);
		}
  //      $link = getInfo($_REQUEST['link']);
        
    }
    
    private function _get_top() {
    	vendor('Itaoke.TopClient');
    	vendor('Itaoke.RequestCheckUtil');
    	vendor('Itaoke.Logger');
    	$top = new \TopClient;
    	$top->appkey = $this->_tbconfig['app_key'];
    	$top->secretKey = $this->_tbconfig['app_secret'];
    	return $top;
    }
    
    public function edit()
    {
        if (IS_POST) {
            if (false === ($pid = $this->_brandmod->create())) {
                $this->error($this->_brandmod->getError());
            }
            if (!$pid['cate_id'] || !trim($pid['cate_id'])) {
                $this->error('请选择商品分类');
            }
            $sid = $pid['id'];
                        $pid['start_time'] = strtotime($_POST['start_time']);
            $pid['end_time'] = strtotime($_POST['end_time']);
            $this->_brandmod->where(array('id' => $sid))->save($pid);
            $this->success(L('operation_success'));
        } else {
            $coll = $this->_get('id', 'intval');
            $article = $this->_brandmod->where(array('id' => $coll))->find();
            $spid = $this->_cate_mod->where(array('id' => $article['cate_id']))->getField('spid');
            if ($spid == 0) {
                $spid = $article['cate_id'];
            } else {
                $spid .= $article['cate_id'];
            }
            $this->assign('selected_ids', $spid);
            $this->assign('info', $article);
            $orig_list = M('ItemsOrig')->select();
            $this->assign('orig_list', $orig_list);
            $this->display();
        }
    }
    public function pass()
    {
        if (IS_POST) {
            $pid['pass'] = $this->_post('pass', 'intval');
            $ids = $this->_post('ids');
            $ids_arr = explode(',', $ids);
            $data['pass'] = $pid['pass'];
            $this->_brandmod->where(array('id' => array('in', $ids)))->save($data);
            $this->ajaxReturn(1, L('operation_success'), '', 'pass');
        } else {
            $ids = trim($this->_request('id'), ',');
            $this->assign('ids', $ids);
            $resp = $this->fetch();
            $this->ajaxReturn(1, '', $resp);
        }
    }
    public function delete_search()
    {
        if (isset($_REQUEST['dosubmit'])) {
            if ($_REQUEST['isok'] == '1') {
                $where = '1=1';
                $title = trim($_POST['title']);
                $cate_id = trim($_POST['cate_id']);
                $nick = trim($_POST['nick']);
                $time_start = trim($_POST['time_start']);
                $time_end = trim($_POST['time_end']);
                $xy = trim($_POST['xy']);
                $min_price = trim($_POST['min_price']);
                $max_price = trim($_POST['max_price']);
                if ($title != '') {
                    $where .= ' AND title LIKE \'%' . $title . '%\'';
                }
                if ($cate_id != '' && $cate_id != 0) {
                    $where .= ' AND cate_id=' . $cate_id;
                }
                if ($time_start != '') {
                    $add_time_start = strtotime($time_start);
                    $where .= ' AND add_time>=\'' . $add_time_start . '\'';
                }
                if ($time_end != '') {
                    $add_time_end = strtotime($time_end);
                    $where .= ' AND add_time<=\'' . $add_time_end . '\'';
                }
                if ($xy != '') {
                    $where .= ' AND xy=' . $xy;
                }
                if ($nick != '') {
                    $where .= ' AND nick LIKE \'%' . $nick . '%\'';
                }
                if ($sellerId != '') {
                    $where .= ' AND sellerId=' . $sellerId;
                }
                $isok = $this->_brandmod->where($where)->select();
                $ids = '';
                foreach ($isok as $val) {
                    $ids .= $val['id'] . ',';
                }
                if ($ids != '') {
                    $ids = substr($ids, 0, -1);
                }
                $this->_brandmod->where($where)->delete();
                $this->success('删除成功', U('brand/clear'));
            } else {
                $this->success('确认是否要删除？', U('brand/clear'));
            }
        } else {
            $this->display();
        }
    }
    public function ajaxgetid()
    {
        $url = $this->_get('url', 'trim');
        if ($url == '') {
            $this->ajaxReturn(0, l('please_input') . l('correct_itemurl'));
        }
        if (!$this->get_id($url)) {
            $this->ajaxReturn(0, l('please_input') . l('correct_itemurl'));
        }
        $itemurl = $this->get_id($url);
        $iid = m('items')->where(array('num_iid' => $itemurl))->find();
        if ($iid) {
            $this->ajaxReturn(1005, l('item_exist'));
        }
        import("ITK.Itklib.itemcollect");
        $itemcollect = new \itemcollect();
        $itemcollect->url_parse($url);
        if ($article = $itemcollect->fetch_tb()) {
            $this->ajaxReturn(1, '', $article);
        }
        $this->ajaxReturn(0, l('item_not_excute'));
    }
    public function get_id($url)
    {
        $coll = 0;
        $get_id = parse_url($url);
        if (isset($get_id['query'])) {
            parse_str($get_id['query'], $item_id);
            if (isset($item_id['id'])) {
                $coll = $item_id['id'];
                return $coll;
            }
            if (isset($item_id['item_id'])) {
                $coll = $item_id['item_id'];
                return $coll;
            }
            if (isset($item_id['default_item_id'])) {
                $coll = $item_id['default_item_id'];
            }
        }
        return $coll;
    }
    
    public function http($url)
    {
        set_time_limit(0);
        $result = file_get_contents($url);
        if ($result === false) {
            $curl_init = curl_init();
            curl_setopt($curl_init, CURLOPT_URL, $url);
            curl_setopt($curl_init, CURLOPT_HEADER, false);
            curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl_init);
            curl_close($curl_init);
        }
        if (empty($result)) {
            $result = false;
        }
        return $result;
    }
        
}